import technicianSelector from '@/components/afterSales/technicianSelector'
import { AddMobileContactData } from '@/utils/common-api.js'
export default {
  data() {
    return {
      more: false,
      statusList: [
        {
          id: 0,
          name: '待确认',
        },
        {
          id: 5,
          name: '待付款',
        },
        {
          id: 10,
          name: '已取消',
        },
        {
          id: 20,
          name: '待备货',
        },
        {
          id: 30,
          name: '待到店',
        },
        {
          id: 40,
          name: '待施工',
        },
        {
          id: 50,
          name: '施工中',
        },
        {
          id: 60,
          name: '已完成',
        },
      ],
      tipShow: false,
      // 页面数据
      dataObj: {
        servicelist: [],
      },
      Pregoods: false,
      // 备货信息
      prepareGoods: [],
      sendWork: false, //派工状态
      pageFrom: '', //上一页
    }
  },
  components: {
    technicianSelector,
  },
  onLoad(options) {
    this.orderid = options.id
    this.pageFrom = options.pageFrom ? options.pageFrom : ''
    this.GetBusOrderDetails()
    this.getOrderStockUpInfomation()
  },

  methods: {
    // 获取详情信息
    GetBusOrderDetails() {
      let data = {
        orderid: this.orderid,
      }
      this.$api.afterSales
        .GetBusOrderDetails(data)
        .then(res => {
          // console.log(res)
          this.dataObj = res.data
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 返回状态
    returnStatus(id) {
      let status = ''
      this.statusList.forEach(it => {
        if (it.id === id) {
          status = it.name
        }
      })
      return status
    },
    returnTime(time) {
      if (time) {
        return time.split('T')[0] + ' ' + time.split('T')[1]
      }
    },
    // 复制
    copy(data) {
      uni.setClipboardData({
        data: data,
        success: function () {
          console.log('success')
          uni.showToast({
            title: '复制成功',
          })
        },
      })
    },
    returntrim(id) {
      if (id) {
        let ids = id.replace(/\s/g, '').replace(/(.{4})/g, '$1 ')
        return ids
      }
    },

    // // 返回预约时间
    // returnyyTime(time) {
    //   if (time) {
    //     var now = new Date(time)
    //     var str = '周' + '日一二三四五六'.charAt(now.getDay())
    //     return (
    //       time.split('T')[0] +
    //       ' ' +
    //       time.split('T')[1].split(':')[0] +
    //       ':' +
    //       time.split('T')[1].split(':')[1] +
    //       ' ' +
    //       str
    //     )
    //   }
    // },
    getUrlParam(url) {
		  let obj = {}
		  let str = url.split('?')[1].split('&')
		  for (let i = 0; i < str.length; i++) {
		      let a = str[i].split('=')
		      obj[a[0]] = a[1]
		  }
		  return obj
    },
    // 扫码
    scan() {
      uni.scanCode({
        success: res => {
          let orderNo =this.getUrlParam(res.result)
          console.log(orderNo.id, this.orderid)
          // 如果扫码出来的订单id与当前id相同则执行下一步
          if (orderNo.id === this.dataObj.order_no) {
            uni.showLoading({
              title: '加载中',
            })
            this.$api.afterSales
              .getArrivalInfo({
                carNum: '',
                mobile: '',
                orderNo: orderNo.id,
              })
              .then(res => {
                if (res.data.userInfo) {
                  this.$store.commit(
                    'afterSales/setUserInfo',
                    res.data.userInfo
                  )
                }
                this.$store.commit('afterSales/setServeAndQueue', {
                  service: res.data.service,
                  queue: res.data.queue,
                })
                if (res.data.carList.length) {
                  this.$store.commit(
                    'afterSales/setArrivalCar',
                    res.data.carList[0]
                  )
                  this.$store.commit('afterSales/setCarList', res.data.carList)
                }
                if (res.data.userInfo && res.data.userInfo.orderCount > 0) {
                  uni.navigateTo({
                    url:
                      '/pages_afterSales/createToStoreRecord/createToStoreRecord?isPackage=0',
                  })
                } else {
                  this.tipShow = true
                }
                uni.hideLoading()
              })
              .catch(err => {
                uni.hideLoading()
              })
          } else {
            uni.showToast({
              title: '核销订单非当前订单，请核对后再试！',
              icon: 'none',
            })
          }
        },
        fail(err) {
          console.log(err)
        },
      })
    },
    // 点击温馨提示的我知道了按钮
    okey() {
      this.tipShow = false
      uni.navigateTo({
        url:
          '/pages_afterSales/createToStoreRecord/createToStoreRecord?isPackage=0',
      })
    },
    selectImg(index) {
      const _this = this
      uni.showActionSheet({
        itemList: ['拍照', '打开相册'],
        success(res) {
          const cameraType = res.tapIndex ? 'album' : 'camera'
          uni.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: [cameraType], // 从相册选择
            success: function (result) {
              uni.showLoading({
                title: '图片上传中~',
              })
              _this.$api.files
                .uploadImg({
                  filePath: result.tempFilePaths[0],
                })
                .then(res => {
                  _this.$set(
                    _this.prepareGoods[index],
                    'stock_up_img',
                    res.baseUrl + res.url
                  )
                  // _this.$set(
                  //   _this.selected[_this.current],
                  //   'detection_State',
                  //   2
                  // )

                  uni.hideLoading()
                })
                .catch(err => {
                  uni.hideLoading()
                  console.log(1, err)
                  uni.showToast({
                    title: '图片上传失败，请稍后重试',
                    icon: 'none',
                  })
                })
            },
          })
        },
      })
      this.prepareGoods = _this.prepareGoods
    },

    // 备货入库
    PreGoods() {
      let data = {
        order_id: this.orderid,
        goods_list: [],
      }
      let status = true
      // // 判断进货价为0时不能备货
      // this.prepareGoods.forEach(it => {
      //   if (it.in_Price !== 0) {
      //     // console.log(it.in_Price)
      //     let newVal = {
      //       in_Price: it.in_Price,
      //       order_snapshoot_id: it.order_snapshoot_id,
      //       stock_up_img: it.stock_up_img,
      //     }
      //     data.goods_list.push(newVal)
      //   } else {
      //     status = false
      //     return false
      //   }
      // })
      if (status) {
        this.$api.afterSales
          .OrderStockUp(data)
          .then(res => {
            console.log(res)
            this.Pregoods = false
            uni.showToast({
              title: '已备货入库',
              icon: 'success',
              duration: 2000,
            })
            setTimeout(() => {
              uni.navigateBack(1)
            }, 2000)
            // this.prepareGoods = res.data
          })
          .catch(err => {
            console.log(err)
          })
      } else {
        uni.showToast({
          title: '请输入商品进货价',
          icon: 'none',
          duration: 2000,
        })
      }
    },
    // 获取备货信息
    getOrderStockUpInfomation() {
      let data = {
        order_id: this.orderid,
      }
      this.$api.afterSales
        .OrderStockUpInfomation(data)
        .then(res => {
          // console.log(res)
          this.prepareGoods = res.data
          this.prepareGoods.forEach(it => {
            if (it.in_Price === 0) {
              it.isWrite = false
            } else {
              it.isWrite = true
            }
          })
        })
        .catch(err => {
          console.log(err)
        })
    },
    // 派工 选择技师
    selTechnician(e) {
      console.log(e)
      // if (e) {
      let data = {
        workId: e.accountId,
        orderId: this.orderid,
      }
      this.$api.afterSales
        .doDispatch(data)
        .then(res => {
          console.log(res)
          uni.showToast({
            title: '操作成功，已派工！',
            duration: 2000,
          })
          setTimeout(() => {
            uni.navigateBack(1)
          }, 2000)
        })
        .catch(err => {
          console.log(err)
        })
      // }
      this.sendWork = false
    },
    closeAll() {
      this.more = false
      this.sendWork = false
    },
    //联系买家
    contactSeller() {
      if (this.pageFrom === 'chat') {
        uni.navigateBack()
        return
      }
      console.log(this.dataObj.maintenancetype)
      let imgSrc
      if (this.dataObj.maintenancetype.length) {
        imgSrc = this.dataObj.maintenancetype[0].goodsDetailslist[0].goods_pic
      } else {
        imgSrc = this.dataObj.brand_img
      }
      AddMobileContactData(this.$store.state.userInfoDetail.store.storeId)
      // 传和我聊天人的信息
      this.$store.commit('news/createConversationActive', {
        user: this.dataObj.account_name, //店铺名称
        img: this.dataObj.headportrait, //店铺头像
        lastTime: '', //
        userId: this.dataObj.account_id, //店铺id
        conversationID: 'C2C' + this.dataObj.account_id,
      })
      this.$store.commit('news/setCardInfo', {
        imgSrc: imgSrc,
        name: '维保商品/服务订单',
        subName:
          '内含' +
          (this.dataObj.servicelist.length +
            this.dataObj.maintenancetype.length) +
          '项',
        discounts: this.dataObj.discounts,
        price: this.dataObj.amount_payable,
        type: 'afterSales',
      })
      uni.navigateTo({
        url:
          '/pages_news/contactSeller/contactSeller?user=' +
          this.dataObj.account_name +
          '&pageId=' +
          this.dataObj.id +
          '&tab=0',
      })
    },
    //打电话
    phoneClick(phone) {
      AddMobileContactData(this.$store.state.userInfoDetail.store.storeId)
      uni.makePhoneCall({
        phoneNumber: phone, //仅为示例
      })
    },
    returnPayTyper(type) {
      let txt = ''
      if (type === 0) {
        txt = '支付宝'
      } else if (type === 1) {
        txt = '微信'
      } else if (type === 15) {
        txt = '现金'
      } else {
        txt = '余额'
      }
      return txt
    },
  },
}
